<template>
    <div class="class-manage">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item>班级管理</el-breadcrumb-item>
        </el-breadcrumb>

        <el-form :model="searchParams" class="function-area-form" inline>
            <!-- 班级名称筛选项 -->
            <el-form-item label="班级名称" class="filter-form-item">
                <el-input v-model="searchParams.className" placeholder="请输入班级名称" class="filter-input"
                    @keyup.enter="handleFilter" />
            </el-form-item>

            <!-- 课程名称筛选项 -->
            <el-form-item label="课程名称" class="filter-form-item">
                <el-input v-model="searchParams.courseName" placeholder="请输入课程名称" class="filter-input"
                    @keyup.enter="handleFilter" />
            </el-form-item>

            <!-- 带班老师筛选项 -->
            <el-form-item label="带班老师" class="filter-form-item">
                <el-select v-model="searchParams.teacherName" placeholder="请选择" clearable class="filter-select"
                    @change="handleFilter">
                    <el-option label="全部" value="" />
                    <el-option v-for="teacher in teacherList" :key="teacher.id" :label="teacher.teacherName"
                        :value="teacher.teacherName" />
                </el-select>
            </el-form-item>

            <!-- 班级状态筛选项 -->
            <el-form-item label="班级状态" class="filter-form-item">
                <el-select v-model="searchParams.classStatus" placeholder="请选择" clearable class="filter-select"
                    @change="handleFilter">
                    <el-option label="全部" value="" />
                    <el-option label="学习中" value="学习中" />
                    <el-option label="毕业" value="毕业" />
                </el-select>
            </el-form-item>
        </el-form>

        <div class="filter-actions">
            <div class="filter-actions-left">
                <el-button type="primary" @click="handleFilter" :icon="Search">筛选</el-button>
                <el-button @click="resetFilter" :icon="Refresh">重置</el-button>
            </div>
        </div>

        <el-table border :data="classList" style="width: 100%" height="calc(100vh - 300px)" :fit="true" v-loading="loading"
            empty-text="暂无班级数据" highlight-current-row>
            <el-table-column type="index" label="#" width="60" align="center" />
            <el-table-column label="班级名称" align="center">
                <template #default="scope">
                    <el-link underline="never" type="primary" @click="gotoClassDetail(scope.row)">
                        {{ scope.row.className }}
                    </el-link>
                </template>
            </el-table-column>
            <el-table-column label="带班老师" prop="teacherName" align="center" />
            <el-table-column label="课程名称" prop="courseName" align="center" />
            <el-table-column label="班级人数" prop="classSize" align="center">
                <template #default="scope">
                    {{ scope.row.classSize }}人
                </template>
            </el-table-column>
            <el-table-column label="价格" prop="price" align="center" />
            <el-table-column label="班级状态" align="center">
                <template #default="scope">
                    <el-tag :type="scope.row.classStatus === '学习中' ? 'success' : 'info'">
                        {{ scope.row.classStatus }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="120">
                <template #default="scope">
                    <el-button size="small" type="primary" @click="handleSchedule(scope.row)">排课</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="pagination-container">
            <el-pagination background v-model:current-page="currentPage" v-model:page-size="pageSize" :total="total"
                layout="prev, pager, next" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getClassList, getTeacherList } from '../../../api/class/class'
import { ElMessage } from 'element-plus'
import { Search, Refresh } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 班级列表相关变量
const classList = ref([])
const teacherList = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索参数
const searchParams = ref({
    className: '',
    courseName: '',
    teacherName: '',
    classStatus: ''
})

// 跳转到班级详情
const gotoClassDetail = async (classItem) => {
    try {
        const encodedData = encodeURIComponent(JSON.stringify(classItem));
        await router.push(`/jiaoxue/detail?data=${encodedData}`)
    } catch (err) {
        console.error('路由跳转失败:', err)
        ElMessage.error('页面跳转失败，请稍后重试')
    }
}

// 新增：排课处理函数
const handleSchedule = (classRow) => {
    const encodedData = encodeURIComponent(JSON.stringify(classRow))
    router.push(`/jiaoxue/schedule?classData=${encodedData}`)
}

// 获取班级数据
const fetchClassData = async () => {
    try {
        loading.value = true

        const params = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            ...searchParams.value
        }

        Object.keys(params).forEach(key => {
            if (params[key] === '') {
                delete params[key]
            }
        })

        const res = await getClassList(params)

        if (res.code === 200) {
            classList.value = res.rows
            total.value = res.total
        } else {
            ElMessage.error(res.msg || '获取班级数据失败')
        }
    } catch (error) {
        console.error('获取班级数据出错:', error)
        ElMessage.error('网络错误，获取班级数据失败')
    } finally {
        loading.value = false
    }
}

// 获取教师列表
const fetchTeacherList = async () => {
    try {
        const res = await getTeacherList()
        if (res.code === 200) {
            teacherList.value = res.data || res.rows || []
        }
    } catch (error) {
        console.error('获取教师列表失败:', error)
        ElMessage.error('获取教师列表失败')
    }
}

// 筛选处理
const handleFilter = () => {
    currentPage.value = 1
    fetchClassData()
}

// 重置筛选
const resetFilter = () => {
    searchParams.value = {
        className: '',
        courseName: '',
        teacherName: '',
        classStatus: ''
    }
    handleFilter()
}

// 分页处理
const handleSizeChange = (val) => {
    pageSize.value = val
    fetchClassData()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    fetchClassData()
}

onMounted(() => {
    fetchClassData()
    fetchTeacherList()
})
</script>

<style scoped>
.class-manage {
    width: 100%;
    overflow-x: auto;
    box-sizing: border-box;
}

.header {
    padding: 15px 0;
    font-size: 20px;
    color: #333;
}

.function-area-form {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 20px;
    flex-wrap: wrap;
}

.filter-form-item {
    width: 25%;
    margin-right: 0;
    margin-bottom: 0;
}

.filter-input {
    width: 200px;
}

.filter-select {
    width: 200px;
}

.filter-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.filter-actions-left {
    display: flex;
    gap: 10px;
}

:deep(.el-table__row:hover) {
    background-color: #f5f7fa !important;
}

:deep(.el-table__header th) {
    background-color: #f9fafb;
    font-weight: 500;
    color: #666;
}

.pagination-container {
    margin-top: 20px;
    text-align: right;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}

.el-link {
    font-weight: 500;
}

.el-link:hover {
    text-decoration: none;
}

.selected-course {
    color: #165DFF;
    font-weight: 500;
}

.mt-3 {
    margin-top: 15px;
}

.mb-3 {
    margin-bottom: 15px;
}

.ml-2 {
    margin-left: 10px;
}
</style>